﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using CadClient.CadHelpers;
using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
[assembly: XmlConfigurator(ConfigFile = "log4netConfig.config", Watch = true)]
namespace CadClient
{ 
    public class CadClient
    {
        private static Socket clientSocket;
        private readonly ILog log = LogManager.GetLogger(typeof(CadClient));
        public CadClient()
        {
            XmlConfigurator.Configure(new FileInfo("log4netConfig.config"));
        }
        [CommandMethod("ConnectDemo")] 
        public void ConnectDemo()
        {
            #region 连接Revit服务器的IP端口
            //string serverIp = "192.168.10.241";
            //int serverPort = 49152;

            // 获取本机的IP地址
            string serverIp = GetLocalIPAddress();
            // 获取本机空闲的端口号
            int serverPort = GetFreePort();
            #endregion



            #region Cad中绘制直线获取点坐标  
            //var doc = Application.DocumentManager.MdiActiveDocument;
            //var ed = doc.Editor;
            //double startX = 0;
            //double startY = 0;
            //double endX = 100;
            //double endY = 100;
            #endregion
            #region 创建Socket并连接Revit服务器
            //using (var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            //{
            //    try
            //    {

            //        clientSocket.](serverIp, serverPort);


            //        //坐标发送给Revit
            //        var message = $"Line,{startX},{startY},{endX},{endY}";
            //        var data = Encoding.UTF8.GetBytes(message);
            //        clientSocket.Send(data);

            //        //Application.ShowAlertDialog("坐标已发送");

            //    }
            //    catch (System.Exception ex)
            //    {

            //        Application.ShowAlertDialog($"失败：{ex.Message}");
            //    }
            //}
            #endregion



            #region 创建Socket并连接Revit服务器

            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(serverIp, serverPort);
            #endregion
            #region 在Cad中创建直线
            var doc = Application.DocumentManager.MdiActiveDocument;
            var db = doc.Database;
            var ed = doc.Editor;
            var lineList = doc.CreateLine();
            var i = 1;
            string logMessage = "";
            foreach (var line in lineList)
            {
                var startPoint = line.StartPoint;
                var endPoint = line.EndPoint;
                var message = $"{startPoint.X},{startPoint.Y},{endPoint.X},{endPoint.Y},";
                var data = Encoding.UTF8.GetBytes(message);
                clientSocket.Send(data);
                ed.WriteMessage("\n" + message);
                logMessage = $"\n方法*{nameof(ConnectDemo)}*坐标已发送<{i}>次——————[{DateTime.Now}]";
                ed.WriteMessage(logMessage);
                File.AppendAllText("logs.txt", logMessage);

                i++;
                if (i == lineList.Count)
                {
                    File.AppendAllText("logs.txt", "\n——————————————————分隔符————————————");
                }
            }
            #endregion
            log.Info($"\n方法*{nameof(ConnectDemo)}*坐标已发送——————[{DateTime.Now}]");
            //string logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory+"mylogs.txt");
            //if (File.Exists(logFilePath))
            //{
            //    Application.ShowAlertDialog($"日志生成成功,路径：{logFilePath}");
            //}
            //else
            //{
            //    Application.ShowAlertDialog("日志生成失败！");
            //}
        }
        #region
        //private static void ReceiveData()
        //{
        //    Task.Run(() =>
        //    {
        //        while (true)
        //        {

        //        }
        //    });
        //}
        #endregion



        static string GetLocalIPAddress()
        {
            string ipAddress = "";
            // 获取主机名关联的IPHostEntry对象
            IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());

            foreach (IPAddress ip in hostEntry.AddressList)
            {
                // 检查IP地址是否为IPv4地址
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    // 将IP地址转换为字符串
                    ipAddress = ip.ToString();
                    // 找到第一个符合条件的IP地址后跳出循环
                    break;
                }
            }

            return ipAddress;
        }


        #region 获得ip号和端口号
        static int GetFreePort()
        {
            int port = 0;
            // 获取本地计算机的IP网络配置
            IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
            // 获取当前正在使用的TCP端口的终结点列表
            IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();

            // 遍历端口范围（建议根据需求调整范围）
            for (int p = 49152; p <= 65535; p++)
            {
                // 检查端口是否被占用
                if (!IsPortInUse(tcpEndPoints, p))
                {
                    // 找到一个未被占用的端口后赋值给port变量
                    port = p;
                    // 找到第一个符合条件的端口后跳出循环
                    break;
                }
            }

            return port;
        }

        static bool IsPortInUse(IPEndPoint[] endPoints, int port)
        {
            foreach (IPEndPoint endPoint in endPoints)
            {
                // 检查终结点的端口是否与指定的端口相同
                if (endPoint.Port == port)
                {
                    // 如果端口被占用，返回true
                    return true;
                }
            }

            // 如果循环结束后仍未找到匹配的终结点，表示端口未被占用，返回false
            return false;
        }
        #endregion

    }
}
